package com.zoshine.zzg.service;

import com.zoshine.zzg.constant.Session;
import com.zoshine.zzg.dao.*;
import com.zoshine.zzg.exception.AppException;
import com.zoshine.zzg.exception.ErrorMessage;
import com.zoshine.zzg.pojo.*;
import com.zoshine.zzg.pojo.pojostatus.OrderStatus;
import com.zoshine.zzg.pojo.pojostatus.OrderSupplierStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.*;


/**
 * 供应商订单ServiceImpl
 * @author 田沛凌
 * @time 2017年6月23日 下午3:33:53
 */
@Service
@Transactional
public class OrderSupplierService extends BaseService<OrderSupplier> {

	private OrderSupplierDao orderSupplierDao;
	private OrderSupplierDetailDao orderSupplierDetailDao;
	private OrderPrisonerDao orderPrisonerDao;
	private OrderPrisonerDetailDao orderPrisonerDetailDao;
	private OrganizationDao organizationDao;
	private RelationSupplierPrisonerDao relationSupplierPrisonerDao;
	private PrisonerInfoDao prisonerInfoDao;
	private GoodsHistoryDetailDao goodsHistoryDetailDao;
	@Autowired
	public void setOrderSupplierDao(OrderSupplierDao orderSupplierDao) {
		this.orderSupplierDao = orderSupplierDao;
	}
	@Autowired
	public void setOrderSupplierDetailDao(
			OrderSupplierDetailDao orderSupplierDetailDao) {
		this.orderSupplierDetailDao = orderSupplierDetailDao;
	}
	@Autowired
	public void setOrderPrisonerDao(OrderPrisonerDao orderPrisonerDao) {
		this.orderPrisonerDao = orderPrisonerDao;
	}
	@Autowired
	public void setOrderPrisonerDetailDao(
			OrderPrisonerDetailDao orderPrisonerDetailDao) {
		this.orderPrisonerDetailDao = orderPrisonerDetailDao;
	}
    @Autowired
    public void setGoodsHistoryDetailDao(GoodsHistoryDetailDao goodsHistoryDetailDao) {
        this.goodsHistoryDetailDao = goodsHistoryDetailDao;
    }

    @Autowired
	public void setRelationSupplierPrisonerDao(
			RelationSupplierPrisonerDao relationSupplierPrisonerDao) {
		this.relationSupplierPrisonerDao = relationSupplierPrisonerDao;
	}
	@Autowired
	public void setPrisonerInfoDao(PrisonerInfoDao prisonerInfoDao) {
		this.prisonerInfoDao = prisonerInfoDao;
	}

	@Autowired
	public void setOrganizationDao(OrganizationDao organizationDao) {
		this.organizationDao = organizationDao;
	}

	/*public void addOrderSupplier(HttpSession session) {
		//1,查询点单详情数据
        OrderPrisoner op = new OrderPrisoner();
		op.setStatus(OrderStatus.AUTIDED.getValue());
		List<OrderPrisoner> listOrderPrisoner = orderPrisonerDao.selectList(op);
		//2,根据点单数据，查询供应商个数
		 	*//*保存非重复的组织*//*
		Set<Long> listSupplier = new HashSet<>();
		 *//*保存所有点单下的详情*//*
		List<OrderPrisonerDetail> allListOrderPrisonerDetail = new ArrayList<>();
		for (OrderPrisoner orderPrisoner : listOrderPrisoner) {
			 *//*查询订单详情*//*
			List<OrderPrisonerDetail> detail = orderPrisonerDetailDao.selectByOrderPrisonerId(orderPrisoner.getId());
			for (OrderPrisonerDetail dd : detail) {
				allListOrderPrisonerDetail.add(dd);
				 *//*查询商品获取组织*//*
                GoodsHistoryDetail goodsHistoryDetail = goodsHistoryDetailDao.selectByGoodsId(dd.getGoodsId());
				listSupplier.add(goodsHistoryDetail.getOrgId());
			}
		}
		//3,按供应商来拆单
		 *//*临时数组，用于保存生成的关于供应商订单的关系表*//*
		List<OrderSupplier> tempList = new ArrayList<>();
		for (Long su : listSupplier) {
			 *//*找寻同一供应商下的点单详情*//*
			for (OrderPrisonerDetail od : allListOrderPrisonerDetail) {
                GoodsHistoryDetail goodsHistoryDetail = goodsHistoryDetailDao.selectByGoodsId(od.getGoodsId());
				 *//*如果是同一供应商下的商品*//*
				if (su.equals(goodsHistoryDetail.getOrgId())) {
					 *//*根据点单ID查询关系表*//*
					List<RelationSupplierPrisoner> selectByOrderPrisonerId = relationSupplierPrisonerDao.selectByOrderPrisonerId(od.getOrderPrisonerId());
					 *//*分四种情况，1，点单关系表不存在,供应商订单对应的关系表不存在。2，点单关系表不存在，供应商订单对应的关系表存在。
					  * 3,点单关系表存在,供应商订单对应的关系表不存在。
					  * 4，同时存在且交叉。5，同时存在不交叉*//*
					 *//*one Situation*//*
					if (selectByOrderPrisonerId.size() == 0 && tempList.size() == 0) {
						oneMethod(od, su, goodsHistoryDetail, tempList,session);
						continue;
					}
					 *//*two Situation*//*
					if (selectByOrderPrisonerId.size() == 0 && tempList.size() > 0) {
						twoMethod(od, su, goodsHistoryDetail, tempList,session);
						continue;
					}
					 *//*four Situation *//*
					if (selectByOrderPrisonerId.size() > 0 && tempList.size() > 0) {
						twoMethod(od, su, goodsHistoryDetail, tempList,session);
						continue;
					}
				}
			}
		}
		for (OrderPrisoner temp:listOrderPrisoner){
			temp.setStatus(OrderStatus.INDELIVERING.getValue());
			orderPrisonerDao.update(temp);
		}
	}*/

	public void addOrderSupplier(HttpSession session) {
		//1,查询点单详情数据
		OrderPrisoner op = new OrderPrisoner();
		op.setStatus(OrderStatus.AUTIDED.getValue());
		List<OrderPrisoner> listOrderPrisoner = orderPrisonerDao.selectList(op);

		Set<String> areaList = new HashSet<>();
		for (OrderPrisoner orderPrisoner : listOrderPrisoner) {
			areaList.add(orderPrisoner.getArea());
		}
		for (String area : areaList) {

			op.setStatus(OrderStatus.AUTIDED.getValue());
			op.setArea(area);
		    listOrderPrisoner = orderPrisonerDao.selectList(op);

			//2,根据点单数据，查询供应商个数
		 	/*保存非重复的组织*/
			Set<Long> listSupplier = new HashSet<>();
		 /*保存所有点单下的详情*/
			List<OrderPrisonerDetail> allListOrderPrisonerDetail = new ArrayList<>();
			for (OrderPrisoner orderPrisoner : listOrderPrisoner) {
			 /*查询订单详情*/
				List<OrderPrisonerDetail> detail = orderPrisonerDetailDao.selectByOrderPrisonerId(orderPrisoner.getId());
				for (OrderPrisonerDetail dd : detail) {
					allListOrderPrisonerDetail.add(dd);
				 /*查询商品获取组织*/
					GoodsHistoryDetail goodsHistoryDetail = goodsHistoryDetailDao.selectByGoodsId(dd.getGoodsId());
					listSupplier.add(goodsHistoryDetail.getOrgId());
				}
			}
			//3,按供应商来拆单
		 /*临时数组，用于保存生成的关于供应商订单的关系表*/

			List<OrderSupplier> tempList = new ArrayList<>();
			for (Long su : listSupplier) {
		 /*找寻同一供应商下的点单详情*/
				for (OrderPrisonerDetail od : allListOrderPrisonerDetail) {
					GoodsHistoryDetail goodsHistoryDetail = goodsHistoryDetailDao.selectByGoodsId(od.getGoodsId());
			 /*如果是同一供应商下的商品*/
					if (su.equals(goodsHistoryDetail.getOrgId())) {
				 /*根据点单ID查询关系表*/
						List<RelationSupplierPrisoner> selectByOrderPrisonerId = relationSupplierPrisonerDao.selectByOrderPrisonerId(od.getOrderPrisonerId());
				 /*分四种情况，1，点单关系表不存在,供应商订单对应的关系表不存在。2，点单关系表不存在，供应商订单对应的关系表存在。
				  * 3,点单关系表存在,供应商订单对应的关系表不存在。
				  * 4，同时存在且交叉。5，同时存在不交叉*/
				 /*one Situation*/
						if (selectByOrderPrisonerId.size() == 0 && tempList.size() == 0) {
							oneMethod(area, od, su, goodsHistoryDetail, tempList, session);
							continue;
						}
				 /*two Situation*/
						if (selectByOrderPrisonerId.size() == 0 && tempList.size() > 0) {
							twoMethod(area,od, su, goodsHistoryDetail, tempList, session);
							continue;
						}
				 /*four Situation */
						if (selectByOrderPrisonerId.size() > 0 && tempList.size() > 0) {
							twoMethod(area,od, su, goodsHistoryDetail, tempList, session);
							continue;
						}
					}
				}
			}
			for (OrderPrisoner temp : listOrderPrisoner) {
				temp.setStatus(OrderStatus.INDELIVERING.getValue());
				orderPrisonerDao.update(temp);
			}
		}
	}


	private void oneMethod(String area, OrderPrisonerDetail od,Long su,GoodsHistoryDetail  goodsHistoryDetail,List<OrderSupplier> tempList,HttpSession session){
		/*建立供应商订单*/
		OrderSupplier orderSupplier = generateOrderSupplier( area,su,od,session);
		/**/
		generateOrderSupplierDetail(od, orderSupplier, goodsHistoryDetail);
		 /*建立关系表*/
		generateRelationSupplierPrisoner(od, orderSupplier.getId());
		 /*添加到临时表中*/
		 tempList.add(orderSupplier);
	}
	private void twoMethod(String area,OrderPrisonerDetail od,Long su,GoodsHistoryDetail goodsHistoryDetail,List<OrderSupplier> tempList,HttpSession seesion){
		 OrderSupplier os=null;
		 for(OrderSupplier orderSupplier:tempList){
			 if(orderSupplier.getAccountSupplier().equals(su)){
				 os=orderSupplier;
			 }
		 }
		 /*表示此供应商下的订单还没生成*/
		 if(os == null){
			 OrderSupplier orderSupplier = generateOrderSupplier( area,su,od,seesion);
			 /*供应商订单详情表*/
			 generateOrderSupplierDetail(od, orderSupplier, goodsHistoryDetail);
			 /*建立关系表*/
			 generateRelationSupplierPrisoner(od, orderSupplier.getId());
			 /*添加到临时表中*/
			 tempList.add(orderSupplier);

		 }else{
			 /*修改或新增供应商订单详情*/
			 List<OrderSupplierDetail> selectListDetail = orderSupplierDetailDao.selectListDetail(os.getId());
			 /*如果不存在关系表就创建*/
			 List<RelationSupplierPrisoner> selectByOrderSupplierId = relationSupplierPrisonerDao.selectByOrderSupplierId(os.getId());
			 boolean ifCreate=true;
			 for (RelationSupplierPrisoner relationSupplierPrisoner : selectByOrderSupplierId) {
				if(relationSupplierPrisoner.getOrderSupplierId().equals(od.getOrderPrisonerId())){
					ifCreate=false;
				}
			}
			 if(ifCreate){
				 /*建立关系表*/
				generateRelationSupplierPrisoner(od, os.getId());
			 }
			 boolean flg = updateDetail(selectListDetail, od);
			 if(flg){
				 /*表示此商品的对应的供应商订单详情不存在，需新增详情*/
				 generateOrderSupplierDetail(od, os, goodsHistoryDetail);
			 }
		 }
	}
	private OrderSupplier generateOrderSupplier(String area, Long su,OrderPrisonerDetail od,HttpSession session){
		User user =(User)session.getAttribute(Session.LOGIN_USER);
		OrderSupplier orderSupplier=new OrderSupplier();
		 orderSupplier.setId(baseIdWorker.createId());
		 //查询供应商账号
		Organization orgSupplier = organizationDao.selectByPrimaryKey(su);
		orderSupplier.setAccountSupplier(orgSupplier.getId());
		orderSupplier.setSupplierName(orgSupplier.getOrgName());
		 	/*--------------*/
		 //查询监所信息
		OrderPrisoner orderPrisoner=orderPrisonerDao.selectByPrimaryKey(od.getOrderPrisonerId());
		PrisonerInfo prisonerInfo = prisonerInfoDao.selectByPrimaryKey(orderPrisoner.getPrisonerInfo());
		Organization orgPrisons=organizationDao.selectByPrimaryKey(prisonerInfo.getOrgId());
		orderSupplier.setAccountPrisons(prisonerInfo.getOrgId());
		 orderSupplier.setCreateUser(user.getId());
		 orderSupplier.setPrisonsName(orgPrisons.getOrgName());
		 	/*--------------*/
		 orderSupplier.setCreateType(1);
		 orderSupplier.setStatus(OrderSupplierStatus.PENDINGAUDIR.getValue());
		 orderSupplier.setTotalCount(0);
		 orderSupplier.setTotalSell(0);
		 orderSupplier.setTotalDeliver(0);
		 orderSupplier.setTotalSettlement(0);
		 orderSupplier.setArea(area);
		 orderSupplier.setCreateTime(new Date());
		 orderSupplier.setUpdateTime(new Date());
		 orderSupplierDao.insert(orderSupplier);
		return orderSupplier;
	}
	private void generateOrderSupplierDetail(OrderPrisonerDetail od,OrderSupplier orderSupplier,GoodsHistoryDetail goodsHistoryDetail){
		/*供应商订单详情表*/
		OrderPrisoner orderPrisoner = orderPrisonerDao.selectByPrimaryKey(od.getOrderPrisonerId());
		 OrderSupplierDetail orderSupplierDetail=new OrderSupplierDetail();
		 orderSupplierDetail.setId(baseIdWorker.createId());
		 orderSupplierDetail.setOrderSupplierId(orderSupplier.getId());
		 orderSupplierDetail.setAccountSupplier(orderSupplier.getAccountSupplier());
		 orderSupplierDetail.setAccountPrisons(orderSupplier.getAccountPrisons());
        orderSupplierDetail.setGoodsHistoryId(goodsHistoryDetail.getId());
        orderSupplierDetail.setGoodsId(goodsHistoryDetail.getGoodsId());
        orderSupplierDetail.setGoodsCount(od.getGoodsCount());
        orderSupplierDetail.setDeliverCount(0);
        orderSupplierDetail.setGoodsName(goodsHistoryDetail.getGoodsName());
        orderSupplierDetail.setGoodsSellPrice(goodsHistoryDetail.getGoodsSellPrice());
        orderSupplierDetail.setGoodsSettlementPrice(goodsHistoryDetail.getGoodsSettlementPrice());
        orderSupplierDetail.setImg(goodsHistoryDetail.getGoodsImg());
        orderSupplierDetail.setArea(orderPrisoner.getArea());
        orderSupplierDetail.setSubArea(orderPrisoner.getSubArea());

		 orderSupplierDetailDao.insert(orderSupplierDetail);
			/*修改供应商订单的总数量及价格*/
		OrderSupplier orderSupplierTemp = orderSupplierDao.selectByPrimaryKey(orderSupplier.getId());
		orderSupplierTemp.setTotalCount(orderSupplierTemp.getTotalCount()+od.getGoodsCount());
		orderSupplierTemp.setTotalSell(orderSupplierTemp.getTotalSell()+od.getGoodsSellPrice()*od.getGoodsCount());
		orderSupplierTemp.setTotalSettlement(orderSupplierTemp.getTotalSettlement()+od.getGoodsSettlementPrice()*od.getGoodsCount());
		orderSupplierDao.update(orderSupplierTemp);
	}
	private void generateRelationSupplierPrisoner(OrderPrisonerDetail od,Long su){
		 RelationSupplierPrisoner relation=new RelationSupplierPrisoner();
		 relation.setOrderPrisonerId(od.getOrderPrisonerId());
		 relation.setOrderSupplierId(su);
		 relationSupplierPrisonerDao.insert(relation);
	}

	private boolean updateDetail(List<OrderSupplierDetail> selectListDetail,OrderPrisonerDetail od){
		 boolean flg=true;
		OrderPrisoner orderPrisoner = orderPrisonerDao.selectByPrimaryKey(od.getOrderPrisonerId());
		for (OrderSupplierDetail ods : selectListDetail) {
			if(od.getGoodsId().equals(ods.getGoodsId()) && orderPrisoner.getArea().equals(ods.getArea())&& orderPrisoner.getSubArea().equals(ods.getSubArea())){
				/*表示此商品的对应的供应商订单详情已存在，需修改商品数量*/
				OrderSupplierDetail selectOne = orderSupplierDetailDao.selectByPrimaryKey(ods.getId());
				selectOne.setGoodsCount(selectOne.getGoodsCount()+od.getGoodsCount());
				orderSupplierDetailDao.update(selectOne);
				/*
				  // 修改供应商订单的总数量及价格
				 */
				OrderSupplier orderSupplier = orderSupplierDao.selectByPrimaryKey(ods.getOrderSupplierId());
				orderSupplier.setTotalCount(orderSupplier.getTotalCount()+od.getGoodsCount());
				orderSupplier.setTotalSell(orderSupplier.getTotalSell()+od.getGoodsSellPrice()*od.getGoodsCount());
				orderSupplier.setTotalSettlement(orderSupplier.getTotalSettlement()+od.getGoodsSettlementPrice()*od.getGoodsCount());
				orderSupplierDao.update(orderSupplier);
				flg=false;
			}
		}
		return flg;
	}

	/**
	 * 根据供应商订单ID查询详情
	 * @param orderSupplierId (供应商订单ID)
	 */
	public List<OrderSupplierDetail> ListOrderSupplierDetail(Long orderSupplierId) {
		if(orderSupplierId == null){
			throw new AppException(ErrorMessage.ORDER_SUPPLIER_ID_CAN_NOT_NULL);
		}
		return orderSupplierDetailDao.selectListDetail(orderSupplierId);
	}

	/**
	 * 删除供应商订单
	 * @param id 供应商订单ID
	 */
	public void  delOrderSupplier(Long id){
		if(id == null){
			throw new AppException(ErrorMessage.ORDER_SUPPLIER_ID_CAN_NOT_NULL);
		}

	}
}
